package cn.getech.data.development.utils;

import cn.getech.data.development.constant.ConnectTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;

public class PgSqlUtil {

    private Logger log = LoggerFactory.getLogger(PgSqlUtil.class);

    private Connection con;


    private  String  driverName=ConnectTypeEnum.PostgreSQL.getDriverClass();




    public PgSqlUtil(String serverUrl, String port, String dbName, String userName, String password) {
        try {

            String url = ConnectTypeEnum.PostgreSQL.getUrl().replace("<host>", serverUrl).replace("<port>", port).replace("<db_name>",dbName);

            Class.forName(driverName);

            con = DriverManager.getConnection(url, userName, password);
            System.out.println("pgsql url="+url);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    public ResultSet getResultSet(String sql) throws SQLException {
        PreparedStatement sta = con.prepareStatement(sql);
        return sta.executeQuery();
    }

    public void execute(String script) throws SQLException {
        Statement sta = con.createStatement();
        sta.execute(script);
    }

    public void close() {
        try {
            if (con != null) {
                con.close();
            }
        } catch (SQLException e) {
            log.error(e.getMessage());
        }
    }
}
